package com.cx.zhshopping.http.interceptor;


import com.cx.zhshopping.http.BaseResponse;
import com.cx.zhshopping.http.RetrofitClient;
import com.google.gson.Gson;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Call;


public class TokenInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request originalRequest = chain.request();
        Response response = chain.proceed(originalRequest);

        try {
            ResponseBody responseBody = response.body();
            //解决response.body().string();只能打印一次
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset UTF8 = Charset.forName("UTF-8");
            String string = buffer.clone().readString(UTF8);

            BaseResponse baseResponseBean = new Gson().fromJson(string, BaseResponse.class);
            if (baseResponseBean != null) {
                if (baseResponseBean.getStatus()==2) {
                    //token过期
                    //根据RefreshToken同步请求，获取最新的Token
                    String newToken = getNewToken();

                    //使用新的Token，创建新的请求
                    Request newRequest = chain.request()
                            .newBuilder()
                            .header("authToken", newToken)
                            .build();
                    //重新请求
                    return chain.proceed(newRequest);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }


    /**
     * 同步请求方式，根据RefreshToken获取最新的Token
     *
     * @return
     */
    private synchronized String getNewToken() throws IOException {
//        通过一个特定的接口获取新的token，此处要用到同步的retrofit请求
        String newToken = "";
        String paramsRefresh = "";

//        LoginInfo loginInfo = DataRepository.getInstance().getLoginInfo();
//        if (loginInfo != null) {
//            paramsRefresh = loginInfo.getRefreshToken();
//        }
//
//        ApiService apiService = RetrofitClient.getInstance().create(ApiService.class);
//
//
//        Call<BaseResponse<LoginInfo>> refreshToken = apiService.refreshToken();
//        refreshToken.request().newBuilder().header("token", paramsRefresh).build();
//
//        BaseResponse<LoginInfo> responseBean = refreshToken.execute().body();
//        if (responseBean.getStatus()==0) {
//            LoginInfo beanData = responseBean.getData();
//            DataRepository.getInstance().setLoginInfo(beanData);
//
//        }
        return newToken;
    }
}

